package com.clothing.customization.service.impl;

import com.clothing.customization.dto.TaskInfoDTO;
import com.clothing.customization.dto.TaskInfoQueryDTO;
import com.clothing.customization.entity.TaskInfo;
import com.clothing.customization.repository.TaskInfoRepository;
import com.clothing.customization.service.TaskInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import jakarta.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TaskInfoServiceImpl implements TaskInfoService {

    private final TaskInfoRepository taskInfoRepository;

    @Override
    public Page<TaskInfoDTO> getTaskList(TaskInfoQueryDTO queryDTO) {
        Specification<TaskInfo> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (StringUtils.hasText(queryDTO.getTitle())) {
                predicates.add(cb.like(root.get("title"), "%" + queryDTO.getTitle() + "%"));
            }
            if (queryDTO.getOrderId() != null) {
                predicates.add(cb.equal(root.get("orderId"), queryDTO.getOrderId()));
            }
            if (queryDTO.getDesignerId() != null) {
                predicates.add(cb.equal(root.get("designerId"), queryDTO.getDesignerId()));
            }
            if (StringUtils.hasText(queryDTO.getPriority())) {
                predicates.add(cb.equal(root.get("priority"), queryDTO.getPriority()));
            }
            if (StringUtils.hasText(queryDTO.getStatus())) {
                predicates.add(cb.equal(root.get("status"), queryDTO.getStatus()));
            }
            if (queryDTO.getDeadlineStart() != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("deadline"), queryDTO.getDeadlineStart()));
            }
            if (queryDTO.getDeadlineEnd() != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("deadline"), queryDTO.getDeadlineEnd()));
            }
            if (queryDTO.getCreatorId() != null) {
                predicates.add(cb.equal(root.get("creatorId"), queryDTO.getCreatorId()));
            }
            if (StringUtils.hasText(queryDTO.getCreatorRole())) {
                predicates.add(cb.equal(root.get("creatorRole"), queryDTO.getCreatorRole()));
            }
            
            return cb.and(predicates.toArray(new Predicate[0]));
        };

        PageRequest pageRequest = PageRequest.of(queryDTO.getPageNum() - 1, queryDTO.getPageSize(), 
            Sort.by(Sort.Direction.DESC, "createTime"));

        return taskInfoRepository.findAll(spec, pageRequest).map(this::convertToDTO);
    }

    @Override
    public TaskInfoDTO getTaskDetail(Long id) {
        return taskInfoRepository.findById(id)
                .map(this::convertToDTO)
                .orElseThrow(() -> new RuntimeException("任务不存在"));
    }

    @Override
    @Transactional
    public TaskInfoDTO createTask(TaskInfoDTO taskDTO) {
        TaskInfo task = new TaskInfo();
        BeanUtils.copyProperties(taskDTO, task);
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        
        return convertToDTO(taskInfoRepository.save(task));
    }

    @Override
    @Transactional
    public TaskInfoDTO updateTask(Long id, TaskInfoDTO taskDTO) {
        TaskInfo task = taskInfoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("任务不存在"));
        
        BeanUtils.copyProperties(taskDTO, task, "id", "createTime", "creatorId", "creatorRole");
        task.setUpdateTime(LocalDateTime.now());
        
        // 如果任务状态变更为已完成，设置完成时间
        if ("completed".equals(taskDTO.getStatus()) && task.getCompletionTime() == null) {
            task.setCompletionTime(LocalDateTime.now());
        }
        
        return convertToDTO(taskInfoRepository.save(task));
    }

    @Override
    @Transactional
    public void deleteTask(Long id) {
        if (!taskInfoRepository.existsById(id)) {
            throw new RuntimeException("任务不存在");
        }
        taskInfoRepository.deleteById(id);
    }

    @Override
    @Transactional
    public void updateTaskStatus(Long id, String status) {
        TaskInfo task = taskInfoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("任务不存在"));
        task.setStatus(status);
        task.setUpdateTime(LocalDateTime.now());
        
        // 如果任务状态变更为已完成，设置完成时间
        if ("completed".equals(status) && task.getCompletionTime() == null) {
            task.setCompletionTime(LocalDateTime.now());
        }
        
        taskInfoRepository.save(task);
    }

    private TaskInfoDTO convertToDTO(TaskInfo task) {
        TaskInfoDTO dto = new TaskInfoDTO();
        BeanUtils.copyProperties(task, dto);
        return dto;
    }
} 